package org.niugang.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


@Configuration
@EnableWebSecurity
/**
 * 虽然和oauth认证优先级，起了冲突但是启动也会放置不安全的攻击
 * @author niugang
 *
 */
@Order(2)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

	@Autowired
	private UserDetailsService userDetailsService;


	@Override
	protected void configure(HttpSecurity http) throws Exception {
		/**
		   * 不是这种
		   * http
		.authorizeRequests()
		.anyRequest().authenticated()
		.and()
		.formLogin()
		.loginPage("/login") 
		.permitAll(); 
		 */
		http.requestMatchers().antMatchers("/authentication/login","/login","/authentication/failed").antMatchers("/oauth/**").and().authorizeRequests().anyRequest()
				.authenticated().and().formLogin().loginPage("/authentication/login").failureUrl("/authentication/failed").loginProcessingUrl("/login").permitAll() // 自定义登录页面，这里配置了 loginPage, 就会通过
				// LoginController 的 login 接口加载登录页面
				.and().csrf().disable();
	}

	@Override
	@Bean
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}

	/**
	       * 基于密码加密的认证
	 * @param auth
	 * @throws Exception
	 */
	@Autowired
	public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
		// 配置用户信息来源和密码加密策略
		auth.userDetailsService(userDetailsService).passwordEncoder(encoder());
	}

	@Bean
	public BCryptPasswordEncoder encoder() {
		return new BCryptPasswordEncoder();
	}

}
